import datetime
import os
import re
import sys

import xbmc,xbmcaddon,xbmcgui,xbmcplugin,xbmcgui
import xbmcvfs
dbg = False

try:
    from addon.common.net import Net
    from addon.common.addon import Addon
except Exception, e:
    xbmc.log('Failed To Import Needed Module: %e') % e
    xbmcgui.Dialog().ok("dij-entertainments-tvshows Import Failure", "Failed to import needed module",
                        "[COLOR red]%e[/COLOR]", "") % e

net = Net()

base_url = 'http://dij-entertainments-tvshows.googlecode.com/svn/trunk/list/Main.xml'
no_image = 'https://corsetsandcutlasses.files.wordpress.com/2013/12/cover-not-yet-available.jpg'
twit_image = 'http://icons.iconarchive.com/icons/iconshock/vector-twitter/256/twitter-bird-landing-icon.png'
twit_fan = 'http://themebin.files.wordpress.com/2010/04/twitter_chat.jpg'
twit_url = 'http://twitrss.me/twitter_user_to_rss/?user=@dijentertainmen'

addon_id = 'plugin.video.dij-entertainments-tvshows'
addon = Addon(addon_id, sys.argv)
Addon = xbmcaddon.Addon(addon_id)

sys.path.append(os.path.join(addon.get_path(), 'resources', 'lib'))
data_path = addon.get_profile()
cookie_file = os.path.join(data_path, 'bu.cookie')

name = addon.queries.get('name', '')
url = addon.queries.get('url', '')
alt = addon.queries.get('alt', '')
mode = addon.queries['mode']
img = addon.queries.get('img', '')

        




def CONTENT(url):
    try:
        html = net.http_GET(url).content
    except:
        Error()

    items = re.findall(r'<name>(.*?)</name>.*?<thumb>(.*?)</thumb>.*?<url>(.*?)</url>', html, re.I|re.DOTALL)
    totalitems=len(items)
    for name, thumb, url in items:
        if thumb == '':
            thumb = no_image
        if url == 'sub':
            subs = re.findall(r'\<startsubs\>(.*?)\<\/endsubs\>', html, re.I|re.DOTALL)

            if subs:
                addon.add_item({'mode': 'subs', 'url': subs, 'name': name}, {'title': name}, img = thumb, resolved=False,
                              total_items=totalitems, item_type='video', is_folder=False)
            
        addon.add_item({'mode': 'resolve', 'url': url}, {'title': name}, img = thumb, resolved=False,
                      total_items=totalitems, item_type='video', is_folder=False)
    xbmc.executebuiltin("Container.SetViewMode(500)")


def SUBS(name,url,img):
    addon.log('SUBS - %s'%name)
    addon.log('SUBS - %s'%url)

    title = name
    res_name = []
    res_url = []
    res_name.append('[COLOR blue]Que All Scenes To Auto Play.[/COLOR]')

    subs = re.findall(r'\<sub\d+\>name\:(.*?\d+)url\:(.*?)\<\/sub\d+\>', url, re.I)
    for name, url in subs:
        res_name.append(name)
        res_url.append(url)

    dialog = xbmcgui.Dialog()
    ret = dialog.select(title.title()+' Select Scene',res_name)

    #if ret == 0:
        
    
        
            


    
    
    
            
            
    

        
def Announce(date,announce):
    date = re.sub(r'/','-', date)
    if addon.get_setting('seen_anounce') == 'true':
        seen_date = addon.get_setting('seen_date')
        if date > seen_date:    pass
        else:   return
    
    from pyxbmct.addonwindow import *
    
    Addon.setSetting('seen_anounce', value='true')
    
    window = AddonDialogWindow('dij-entertainments-tvshows [COLOR red]*ANNOUNCEMENT*[/COLOR] %s'%date)
    window.setGeometry(850, 600, 12, 8)
    image = Image(addon.get_icon())
    window.placeControl(image, 0, 0, rowspan=3, columnspan=2)
    textBox = TextBox(textColor='0xFFFFFFFF')
    window.placeControl(textBox, 3, 0, columnspan=7, rowspan=11)
    textBox.setText(announce)

    button = Button('Close')
    window.placeControl(button, 11, 3, columnspan=2)
    window.setFocus(button)
    window.connect(button, window.close)
    window.connect(ACTION_NAV_BACK, window.close)
    window.doModal()
    Addon.setSetting(id='seen_date', value=date)
        
def RESOLVE(url, img):
    
    if re.search('\.mp4', url, re.I):
        play(url,img)

    elif re.search('\<ALT\>', url):
        r = re.split('\<ALT>', url)
        url = str(r[0])
        alt_url = str(r[1])

    '''Thank you to Eldorado and all thee Users that have helped to
       keep Urlresolver updated.'''

    import urlresolver 
    stream_url = urlresolver.HostedMediaFile(url=url).resolve()

    if not stream_url or not isinstance(stream_url, basestring):
        if alt_url != '':
            addon.log( 'RESOLVE FAILED, %s, Using Alt, %s' %(url,alt_url)) 
            stream_url = urlresolver.HostedMediaFile(url=alt_url).resolve()
        
    play(stream_url,img)


        

def play(url,img):
    listitem = xbmcgui.ListItem(path=str(url), iconImage=img, thumbnailImage=img)
    listitem.setProperty('IsPlayable', 'true')
    listitem.setPath(str(url))
    xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, listitem)
    return True
    
        



elif mode=='CONTENT':
    CONTENT(url)
elif mode=='resolve':
    RESOLVE(url, img)
elif mode=='subs':
    SUBS(name,url,img)
elif mode=='twitter':
    utils.TWITTER(url)
#xbmc.executebuiltin("Container.SetViewMode(50)")
xbmcplugin.endOfDirectory(int(sys.argv[1]))

